#!/usr/bin/env ruby
require 'csv'
require 'config/environment'
require 'lib/group_excel'
#
#   This script takes 1 argument, locaction of XLS files which contain the student rosters
#   If any errors occur, it will notify you on the screen
#   The only assumption is that all the csv files are student roster files
#   To run this file, from the main directory, type script/student_update location/of/csv/folder
#

# There's a lot of crap in this file which may or may not get cleaned up.  

errors = []
reasons = []
count = 0

#how to get files?
directory = ARGV[0]
puts directory

%x[ls "#{directory}"].each do |file|
  puts file
  next unless file[file.length-4,3]=='xls'
  full_path = "#{directory}#{file}".strip
  puts full_path
  begin
    excel_group = StudentExcel.new(full_path)
  rescue
    print "error loading file #{full_path}"
    next
  end
  site = Site.find_by_name(excel_group.school)
  next unless site
  user = User.find_by_site_id("#{site.id}")
  group = Group.find_by_name_and_site_id(excel_group.class, "#{site.id}")
  unless group
    Group.new({'site_id'=> site.id, 'name'=>"#{excel_group.class}", 'description'=>"#{excel_group.class}", 'lap'=>1, "user_id"=>user.id}).save!
    group = Group.find_by_name_and_site_id("#{excel_group.class}", "#{site.id}")
  end
  excel_group.students.each do |student|
    r = Runner.find_by_first_name_and_last_name_and_shoe_size(student['first_name'], student['last_name'], student['shoe_size'])
    if not r
      r = Runner.new
      r.last_name=student['last_name']
      r.first_name=student['first_name']
      r.gender=student['gender'].upcase
      r.level=student['grade']
      r.shirt_size = student['t_shirt_size']
      r.shoe_size = student['shoe_size']
      r.goal = student.fetch('goal', 26.2)
      r.group_id = group.id
      birthdate= Time.parse(student[dob])
      r.save()
    else
      r.group_id = group.id
      r.save()
    end
  end
end

